package com.ruoyi.web.controller.examine.store;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.RestaurantStoreResource;
import com.ruoyi.common.core.domain.entity.StoreExamine;
import com.ruoyi.common.core.domain.entity.StoreExamineDetail;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.RestaurantStoreResourceService;
import com.ruoyi.system.service.StoreExamineDetailService;
import com.ruoyi.system.service.StoreExamineService;
import com.ruoyi.system.service.resp.StoreExamineDetailDTO;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/examine/store/storeExamineDetail")
public class StoreExamineDetailController extends BaseController {
    @Resource
    private StoreExamineDetailService storeExamineDetailService;

    @Resource
    private StoreExamineService storeExamineService;

    @Resource
    RestaurantStoreResourceService restaurantStoreResourceService;

    @Log(title = "点餐质检", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(StoreExamineDetail examinePlan)
    {
        startPage();
        List<StoreExamineDetail> list = storeExamineDetailService.selectList(examinePlan);
        return getDataTable(fillToDTO(list));
    }


    @Log(title = "点餐质检All", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(StoreExamineDetail examinePlan)
    {
        List<StoreExamineDetail> list = storeExamineDetailService.selectList(examinePlan);
        return getDataTable(fillToDTO(list));
    }



    @Log(title = "点餐质检All", businessType = BusinessType.OTHER)
    @GetMapping("/listResourceAll")
    public TableDataInfo listResourceAll(RestaurantStoreResource examinePlan)
    {
        List<RestaurantStoreResource> list = restaurantStoreResourceService.selectRestaurantStoreResourceList(examinePlan);
        return getDataTable((list));
    }


    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return success(fillOneToDTO(storeExamineDetailService.selectById(id)));
    }

    @Log(title = "点餐质检", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody StoreExamineDetail examinePlan)
    {
        examinePlan.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = storeExamineDetailService.create(examinePlan);
        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "点餐质检", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody StoreExamineDetail examinePlan) {
        examinePlan.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = storeExamineDetailService.update(examinePlan);
        if (!result) {
            return error();
        }
        processExamineStatus(examinePlan.getId());
        return success();
    }

    private void processExamineStatus(Long examineDetailId) {
        StoreExamineDetail storeExamineDetail = storeExamineDetailService.selectById(examineDetailId);
        if (storeExamineDetail == null) {
            return;
        }
        StoreExamine storeExamine = storeExamineService.selectById(storeExamineDetail.getExamineId());
        if (storeExamine == null) {
            return;
        }
        StoreExamine storeExamineUpdate = new StoreExamine();
        storeExamineUpdate.setId(storeExamine.getId());
        List<StoreExamineDetail> storeExamineDetails = storeExamineDetailService.selectList(StoreExamineDetail.builder().examineId(storeExamineDetail.getExamineId()).build());
        if (CollectionUtils.isEmpty(storeExamineDetails)) {
            storeExamineUpdate.setStatus("没有检测明细");
            storeExamineService.update(storeExamineUpdate);
            return;
        }
        int failCnt = 0;
        int successCnt = 0;
        for (StoreExamineDetail detail : storeExamineDetails) {
            if ("检测通过".equals(detail.getStatus())) {
                successCnt = successCnt + 1;
            } else if ("检测不通过".equals(detail.getStatus())) {
                failCnt = failCnt + 1;
            }
        }
        if (failCnt > 0) {
            storeExamineUpdate.setStatus("检测不通过");
            storeExamineService.update(storeExamineUpdate);
        } else if (storeExamineDetails.size() == successCnt) {
            storeExamineUpdate.setStatus("检测通过");
            storeExamineService.update(storeExamineUpdate);
        } else {
            storeExamineUpdate.setStatus("检测中");
            storeExamineService.update(storeExamineUpdate);
        }
    }

    @Log(title = "点餐质检", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(storeExamineDetailService.deleteById(id));
    }


    private List<StoreExamineDetailDTO> fillToDTO(List<StoreExamineDetail> normalExamines) {
        PageInfo oldPage = new PageInfo(normalExamines);
        Page<StoreExamineDetailDTO> newPage = new Page<>();
        newPage.setTotal(oldPage.getTotal());
        if (CollectionUtils.isEmpty(normalExamines)) {
            newPage.addAll(Collections.emptyList());
            return newPage;
        }
        List<Long> resourceId = normalExamines.stream().map(StoreExamineDetail::getResourceId).collect(Collectors.toList());
        Map<Long, RestaurantStoreResource> resourceMap = restaurantStoreResourceService.selectRestaurantStoreResourceByIds(resourceId).stream().collect(Collectors.toMap(RestaurantStoreResource::getId, g -> g));
        List<StoreExamineDetailDTO> storeExamineDetailDTOS = normalExamines.stream().map(g -> {
            StoreExamineDetailDTO normalExamineDTO = new StoreExamineDetailDTO();
            normalExamineDTO.setId(g.getId());
            normalExamineDTO.setResourceId(g.getResourceId());
            normalExamineDTO.setResourceName(Optional.ofNullable(resourceMap.get(g.getResourceId())).map(RestaurantStoreResource::getName).orElse(null));
            normalExamineDTO.setContent(g.getContent());
            normalExamineDTO.setStatus(g.getStatus());
            normalExamineDTO.setCreateBy(g.getCreateBy());
            normalExamineDTO.setCreateTime(g.getCreateTime());
            normalExamineDTO.setUpdateBy(g.getUpdateBy());
            normalExamineDTO.setUpdateTime(g.getUpdateTime());
            return normalExamineDTO;
        }).collect(Collectors.toList());
        newPage.addAll(storeExamineDetailDTOS);
        return newPage;
    }


    private StoreExamineDetailDTO fillOneToDTO(StoreExamineDetail normalExamine) {
        if (normalExamine == null) {
            return null;
        }
        RestaurantStoreResource buffetExamine = restaurantStoreResourceService.selectRestaurantStoreResourceById(normalExamine.getResourceId());
        StoreExamineDetailDTO normalExamineDTO = new StoreExamineDetailDTO();
        normalExamineDTO.setId(normalExamine.getId());
        normalExamineDTO.setResourceId(normalExamine.getResourceId());
        normalExamineDTO.setCreateBy(normalExamine.getCreateBy());
        normalExamineDTO.setCreateTime(normalExamine.getCreateTime());
        normalExamineDTO.setUpdateBy(normalExamine.getUpdateBy());
        normalExamineDTO.setUpdateTime(normalExamine.getUpdateTime());
        if (buffetExamine != null) {
            normalExamineDTO.setResourceName(buffetExamine.getName());
        }
        return normalExamineDTO;
    }

}
